<template>
  <div class="home-page">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div class="nav-tabs">
        <span class="nav-tab" :class="{ active: activeTab === 'follow' }" @click="activeTab = 'follow'">
          关注
        </span>
        <span class="nav-tab" :class="{ active: activeTab === 'discover' }" @click="activeTab = 'discover'">
          发现
        </span>
        <span class="nav-tab" :class="{ active: activeTab === 'local' }" @click="activeTab = 'local'">
          杭州
        </span>
      </div>
      <div class="nav-actions">
        <button class="customer-service-btn" @click="goToCustomerService">💬 在线咨询</button>
        <button class="service-admin-btn" @click="goToServiceAdmin">👨‍💼 人工客服</button>
        <div class="search-icon">🔍</div>
      </div>
    </header>

    <!-- 内容分类导航 -->
    <div class="category-nav">
      <div class="category-list">
        <span 
          v-for="category in categories" 
          :key="category"
          class="category-item"
          :class="{ active: activeCategory === category }"
          @click="handleCategoryChange(category)"
        >
          {{ category }}
        </span>
        <span class="category-more">▼</span>
      </div>
    </div>

    <!-- 主内容区域 -->
    <main class="content-area">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
      
      <!-- 帖子列表 -->
      <div v-else-if="posts.length > 0" class="posts-container">
        <PostCard
          v-for="post in posts"
          :key="post.id"
          :post="post"
          @tag-click="handleTagClick"
        />
        
        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more" @click="loadMore">
          <button class="load-more-btn">加载更多</button>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else class="empty-state">
        <p>暂无内容</p>
      </div>
    </main>

    <!-- 底部导航栏 -->
    <BottomNavigation />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import BottomNavigation from './BottomNavigation.vue'
import PostCard from './PostCard.vue'

const router = useRouter()

const activeTab = ref('discover')
const activeCategory = ref('推荐')
const categories = ['推荐', '摄影', '搞笑', '舞蹈', '旅游', '科技']

// 数据相关
const posts = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(false)
const total = ref(0)

// 获取帖子列表
const fetchPosts = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  
  if (reset) {
    page.value = 1
    posts.value = []
  }
  
  try {
    const params = new URLSearchParams({
      page: page.value.toString(),
      page_size: pageSize.value.toString()
    })
    
    // 如果是推荐以外的分类，添加category参数
    if (activeCategory.value !== '推荐') {
      params.append('category', activeCategory.value)
    }
    
    const url = `http://localhost:8000/api/posts?${params}`
    console.log('[HomePage] 请求URL:', url)
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
    
    console.log('[HomePage] 响应状态:', response.status, response.statusText)
    
    if (!response.ok) {
      const errorText = await response.text()
      console.error('[HomePage] 响应错误内容:', errorText)
      throw new Error(`获取帖子失败: ${response.status} ${response.statusText}`)
    }
    
    const data = await response.json()
    console.log('[HomePage] 响应数据:', data)
    
    // 检查响应数据结构
    // 后端现在直接返回 {posts, total, page, page_size, has_more}
    if (!data || !data.posts) {
      console.error('[HomePage] 响应数据结构不正确:', data)
      throw new Error('响应数据格式错误：缺少 posts 字段')
    }
    
    if (reset) {
      posts.value = data.posts
    } else {
      posts.value.push(...data.posts)
    }
    
    total.value = data.total || 0
    hasMore.value = data.has_more || false
    page.value += 1
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    // 添加用户友好的错误提示
    if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
      alert('无法连接到服务器，请检查：\n1. 后端服务器是否运行在 http://localhost:8000\n2. 网络连接是否正常')
    } else {
      alert(`获取帖子列表失败: ${error.message}`)
    }
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  fetchPosts(false)
}

// 处理分类切换
const handleCategoryChange = (category) => {
  if (activeCategory.value !== category) {
    activeCategory.value = category
    fetchPosts(true)
  }
}

// 处理标签点击（筛选对应标签的帖子）
const handleTagClick = (tag) => {
  // 可以在这里实现标签筛选功能
  // 暂时重新加载当前分类的帖子
  console.log('点击标签:', tag)
  fetchPosts(true)
}

// 跳转到客服聊天页面
const goToCustomerService = () => {
  console.log('[HomePage] 点击在线咨询按钮')
  router.push('/customer-service/chat')
}

// 跳转到人工客服管理页面
const goToServiceAdmin = () => {
  console.log('[HomePage] 点击人工客服按钮')
  router.push('/customer-service/admin')
}

// 组件挂载时加载数据
onMounted(() => {
  fetchPosts(true)
})
</script>

<style scoped>
.home-page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  background: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

/* 顶部导航栏 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-tabs {
  display: flex;
  gap: 24px;
}

.nav-tab {
  font-size: 16px;
  color: #666;
  cursor: pointer;
  padding: 4px 0;
  transition: color 0.2s;
}

.nav-tab.active {
  color: #ff2442;
  font-weight: 600;
}

.nav-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.customer-service-btn {
  background: #ff2442;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.3s;
  white-space: nowrap;
}

.customer-service-btn:hover {
  background: #e01d37;
}

.service-admin-btn {
  background: #2196F3;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.3s;
  white-space: nowrap;
}

.service-admin-btn:hover {
  background: #1976D2;
}

.search-icon {
  font-size: 20px;
  color: #1677ff;
  cursor: pointer;
}

/* 分类导航 */
.category-nav {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

.category-list {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 12px 16px;
  white-space: nowrap;
}

.category-item {
  font-size: 14px;
  color: #666;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 16px;
  transition: all 0.2s;
  white-space: nowrap;
}

.category-item.active {
  color: #ff2442;
  background: #fff0f0;
  font-weight: 500;
}

.category-more {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

/* 主内容区域 */
.content-area {
  flex: 1;
  overflow-y: auto;
  background: #fff;
  -webkit-overflow-scrolling: touch;
  width: 100%;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 14px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #999;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #ff2442;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.posts-container {
  padding: 0;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0;
  width: 100%;
  box-sizing: border-box;
}

.load-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
}

.load-more-btn {
  background: #ff2442;
  color: white;
  border: none;
  padding: 10px 24px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.load-more-btn:hover {
  background: #e01d37;
}

/* 响应式 */
@media (max-width: 768px) {
  .posts-container {
    padding: 0;
    gap: 0;
  }

  .nav-tabs {
    gap: 16px;
  }

  .nav-tab {
    font-size: 15px;
  }
}

@media (min-width: 1200px) {
  .posts-container {
    grid-template-columns: repeat(3, 1fr);
    gap: 0;
    padding: 0;
  }
}
</style>

